#pragma once

#include <iostream>
#include <pthread.h>
#include <vector>
#include <queue>

struct threadinfo
{
    pthread_t td;
    std::string name;
};
const static int defaultnum = 5;
template <class T>
class threadpool
{
    void Lock()
    {
        pthread_mutex_lock(&mutex_);
    }
    void Unlock()
    {
        pthread_mutex_unlock(&mutex_);
    }
    void Wakeup()
    {
        pthread_cond_signal(&cond_);
    }
    void ThreadSleep()
    {
        pthread_cond_wait(&cond_, &mutex_);
    }

public:
    bool IsEmpty()
    {
        return tasks_.empty();
    }
    std::string GetThreadName(pthread_t td)
    {
        for (const auto &ti : threads_)
        {
            if (ti.td == td)
                return ti.name;
        }
        return "None";
    }
    static void *Handlertask(void *args)
    {
        threadpool *tp = static_cast<threadpool *>(args);
        std::string name = tp->GetThreadName(pthread_self());
        while (true)
        {
            tp->Lock();
            if (tp->IsEmpty())
                tp->ThreadSleep();
            T t = tp->Pop();
            tp->Unlock();
            t();
        }
    }
    T Pop()
    {
        T t = tasks_.front();
        tasks_.pop();
        return t;
    }
    void Push(const T &t)
    {
        Lock();
        tasks_.push(t);
        Wakeup();
        Unlock();
    }
    void Start()
    {
        int num = threads_.size();
        for (int i = 0; i < num; i++)
        {
            threads_[i].name = "thread-" + std::to_string(i + 1);
            pthread_create(&(threads_[i].td), nullptr, Handlertask, this);
        }
    }
    static threadpool<T> *GetInstance()
    {
        if (nullptr == tp_)
        {
            pthread_mutex_lock(&lock_);
            if (nullptr == tp_)
            {
                std::cout << "log:sigletion create done first" << std::endl;
                tp_ = new threadpool<T>();
            }
            pthread_mutex_unlock(&lock_);
        }
        return tp_;
    }

private:
    threadpool(int num = defaultnum) : threads_(num)
    {

        pthread_mutex_init(&mutex_, nullptr);
        pthread_cond_init(&cond_, nullptr);
    }
    ~threadpool()
    {
        pthread_mutex_destroy(&mutex_);
        pthread_cond_destroy(&cond_);
    }
    threadpool(const threadpool<T> &) = delete;
    const threadpool<T> &operator=(const threadpool<T> &) = delete;

private:
    std::vector<threadinfo> threads_;
    std::queue<T> tasks_;
    pthread_mutex_t mutex_;
    pthread_cond_t cond_;
    static threadpool<T> *tp_;
    static pthread_mutex_t lock_;
};
template <class T>
threadpool<T> *threadpool<T>::tp_ = nullptr;
template <class T>
pthread_mutex_t threadpool<T>::lock_ = PTHREAD_MUTEX_INITIALIZER;